﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections;

namespace SiGeSIB.Data.Common
{
	public static class Extensions
	{
		private const char ENUM_SEPERATOR_CHARACTER = ',';

		public static string GetDescription(this Enum value)
		{
			// Check for Enum that is marked with FlagAttribute
			var entries = value.ToString().Split(ENUM_SEPERATOR_CHARACTER);
			var description = new string[entries.Length];

			for (var i = 0; i < entries.Length; i++)
			{
				var fieldInfo = value.GetType().GetField(entries[i].Trim());
				var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

				description[i] = (attributes.Length > 0) ? attributes[0].Description : entries[i].Trim();
			}

			return String.Join(", ", description);
		}

		public static bool IsNullOrEmpty(this ICollection enumerable)
		{
			return enumerable == null || enumerable.Count == 0;
		}

        public static bool HasInvalidValue(this DateTime dt)
        {
            return
                dt.Equals(DateTime.MinValue) || dt.Equals(DateTime.MaxValue);
        }

		public static DateTime Truncate(this DateTime dt)
		{
			return new DateTime(dt.Year, dt.Month, dt.Day);
		}

		public static DateTime? Truncate(this DateTime? dt)
		{
			return dt.HasValue ? new DateTime(dt.Value.Year, dt.Value.Month, dt.Value.Day) : (DateTime?)null;
		}
	}
}
